import {defineStore} from 'pinia'
import { reactive, ref } from 'vue'
import {useRoute,useRouter,type RouteLocationNormalizedLoaded} from 'vue-router'
export const useTagsStore=defineStore('TagsStore',()=>{
   let taglist = reactive([{name:'dashboard',path: '/index/dashboard',meta: {title: 'home'}}])
   let router = useRouter()//跳转路由
   /*
   在商品列表下标添加与编辑
   */ 
   function pushtag(route:RouteLocationNormalizedLoaded,index:number=-1){
        let {path,meta:{title},name}=route
           if (name=='redirect') {//过滤掉重定向页面（）
      return
   }
        let opentags=taglist//所有打开的蓝色tag
        let findtag=opentags.find(v=>v.path===path)//tag第一次出现返回und路由否则路由
        if (!findtag) {//第一次出现
         var i=index>-1?index:opentags.length//index大于-1说明不是最后一个tag就将传过来的赋值(也就是原本下标+1)
         opentags.splice(i,0,{path,meta:{title:title as string},name:name as string})//将i开始的0下标替换成添加或者编辑
        }
   }
   /*
   单击标签
   */ 
   function clicktag(index:number){
         const {path}=taglist[index]
         let rou=router.currentRoute.value//当前路由
         if (path!=rou.path) {
            router.push(path)
         }
   }

   /*
   删除标签
   */ 
   function deletetag(index:number){
      let tag = taglist//点击拿到当前所有子路由
      let open_tag = tag[index]//点击拿到当前下标的路由
      let routed=router.currentRoute.value//当前路由
      if (routed.path == open_tag.path) {//路由与点击的下标路由相等
         let { path } = tag[index + 1] || tag[index - 1]//将当面路由下标+1或者-1并跳转，
         router.push(path)
      }
      tag.splice(index, 1)//下标截取一个位置
}
/*
   添加删除关闭按钮
   */ 
function  removebuttom(path:string){
   let removebuttom = taglist//当前所有子路由
   let index=removebuttom.findIndex(item=>item.path==path)
   if (-1!=index) {
      deletetag(index)
   }
}
/*
   关闭所有标签
   */ 
  function closeall(){
   taglist.splice(1)//从1下标删除到末尾
   router.push({path:'/index/dashboard'})//跳转首页
  }
/*
   关闭右侧标签
   */
  function closeright(index:number){
   let closetaglist=taglist
   closetaglist.splice(index+1)//移除当前下标后面所有，但只删除标签路由还没有↓
   //当前列表行tag标签所有路由等于动态路由返回下标(类似最后一个下标)
   let activeindex=closetaglist.findIndex(item=>item.path==router.currentRoute.value.path)
   if (activeindex>index) {//动态路由大于下标
     const {path}= closetaglist[index]
     router.push(path)
   }
  }
/*
   关闭右侧标签
   */
  function Refresh(index:number){
   const {path}=taglist[index]
   router.push({path:'/index/redirect/'+path})//不为空或者未定义就执行右边
  }
   return{taglist,pushtag,clicktag,deletetag,removebuttom,closeall,closeright,Refresh}
},{
   persist:{
      key:'list',
      storage:sessionStorage
   }
})